package com.itgacl.magic4j.libcommon.component.sms.aliyun;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: 孤傲苍狼 290603672@qq.com
 * @Description: 发送短信封装服务实现类
 * @Date: 2020/10/29 15:05
 * @Version: V1.0
 */
@Slf4j
@Service
public class AliyunSmsSenderServiceImpl implements AliyunSmsSenderService {

    @Autowired
    private AliyunSMSConfig smsConfig;

    @Override
    public CommonResponse sendSmsVerificationCode(String phoneNumber, String verificationCode) {
        DefaultProfile profile = DefaultProfile.getProfile(smsConfig.getRegionId(), smsConfig.getAccessKeyId(), smsConfig.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain(smsConfig.getDomain());
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", smsConfig.getRegionId());
        request.putQueryParameter("PhoneNumbers", phoneNumber);
        request.putQueryParameter("SignName", smsConfig.getSignName());
        request.putQueryParameter("TemplateCode", "SMS_217845773");
        // 短信模板变量对应的实际值，JSON格式。
        Map<String, String> templateParamMap = new HashMap<>();
        templateParamMap.put("code", verificationCode);
        request.putQueryParameter("TemplateParam", JSON.toJSONString(templateParamMap));
        try {
            CommonResponse commonResponse = client.getCommonResponse(request);
            return commonResponse;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }
}
